package com.zhiwang.xiaoqu.ui.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import com.zhiwang.xiaoqu.R
import com.zhiwang.xiaoqu.bus.LoginEvent
import com.zhiwang.xiaoqu.bus.LogoutEvent
import com.zhiwang.xiaoqu.bus.NetWorkConnectedEvent
import com.zhiwang.xiaoqu.ui.BaseFragment
import com.zhiwang.xiaoqu.ui.WebViewActivity
import com.zhiwang.xiaoqu.widget.webview.WebViewClientCallBack
import kotlinx.android.synthetic.main.layout_webview.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 对于Fragment的使用，必须时刻注意View为空的情况，因为对于Fragment 很多时候View销毁了，但是Fragment本身实例并未销毁
 * 这个时候Fragment中的一些还未完成的操作在View销毁的情况回调了，回调中必须判断View是否为空在再进行相关操作
 */
class WebViewFragment : BaseFragment() {

    val TAG = "WebViewFragment"

    private var setStatusBar: String = ""
    //初始url
    private lateinit var url: String
    //保存每次页面跳转之后的url
    private lateinit var currUrl: String

    companion object {
        fun newInstance(url: String, title: String): WebViewFragment {
            val args = Bundle().apply {
                putString("URL_KEY", url)
                putString("Title", title)
            }
            val fragment = WebViewFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private val webViewClientCallBack = object : WebViewClientCallBack {
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (request != null) {
                    currUrl = request.url.toString()
                }
                view?.loadUrl(request?.url.toString(), webViewHeader())
                return true
            }
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            if (url != null)
                currUrl = url
            view?.loadUrl(url, webViewHeader())
            return true
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            smartRefresh?.finishRefresh()
            //防止有些情况下 Fragment js 注入失效,使其刷新后再次注入
            masterWebView.webView.addJavascriptInterface(this, "android")
        }

    }


    private val chromeClient = object : WebChromeClient() {

        override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
            return super.onConsoleMessage(consoleMessage)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        url = arguments?.getString("URL_KEY") ?: ""
        currUrl = url
        setStatusBar = arguments!!.getString("Title", "")
        EventBus.getDefault().register(this)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.layout_webview, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        masterWebView.setRetryListener(::loadCurrUrl)
        if (setStatusBar.isNotEmpty())
            webview_title.text = setStatusBar
        else webview_title.visibility = View.GONE
        configWebView()
        loadOriginUrl()
        smartRefresh.setOnRefreshListener {
            loadOriginUrl()

        }
    }

    private fun loadOriginUrl() {
        masterWebView.webView.loadUrl(url, webViewHeader())
        //防止有些情况下 Fragment js 注入失效,使其刷新后再次注入
        masterWebView.webView.addJavascriptInterface(this, "android")
    }

    private fun loadCurrUrl() {
        //防止有些情况下 Fragment js 注入失效,使其刷新后再次注入
        masterWebView.webView.addJavascriptInterface(this, "android")
        masterWebView.webView.loadUrl(currUrl, webViewHeader())
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun configWebView() {
        val settings = masterWebView.webView.settings
        settings.javaScriptEnabled = true
        settings.useWideViewPort = true
        settings.setAppCacheEnabled(true)
        settings.textZoom = 100
        settings.setAppCachePath(context!!.cacheDir.toString())
        masterWebView.webViewClientCallBack = webViewClientCallBack
        masterWebView.webView.webChromeClient = chromeClient
        masterWebView.webView.addJavascriptInterface(this, "android")
    }

    @JavascriptInterface
    fun openLink(url: String, isExternal: String) {
        when (isExternal) {
            "false" -> WebViewActivity.load(context!!, url)
            "true" -> {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                context!!.startActivity(intent)
            }
        }
    }

    @JavascriptInterface
    fun openLinkWithoutTitle(url: String) {
        WebViewActivity.load(context!!, url, false)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLogin(event: LoginEvent) {
        loadOriginUrl()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLogout(event: LogoutEvent) {
        loadOriginUrl()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetWorkReconnected(event: NetWorkConnectedEvent) {
        loadCurrUrl()
    }


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            masterWebView.webView.addJavascriptInterface(this, "android")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}